<?php
session_start();

// Find out where we're installed
$app_root = dirname(dirname(__FILE__));

// Add the include path 
ini_set('include_path', $app_root . '/admin/includes:' . ini_get('include_path'));

// Force UTC
date_default_timezone_set('UTC');

// Get the app config
require $app_root . '/config.php';

require 'Password.class.php';

// DB connect
try {
	$db = Zend_Db::factory($cms_config['db_factory'], array(
	    'host'     => $cms_config['db_host'],
	    'username' => $cms_config['db_user'],
	    'password' => $cms_config['db_pass'],
	    'dbname'   => $cms_config['db_database']
	));
    $db->getConnection();
	$db->query("SET NAMES 'utf8'");
	if (isset($cms_config['zend_profiler']) and $cms_config['zend_profiler']) {
		$db->getProfiler()->setEnabled(true);
	}
} catch (Zend_Db_Adapter_Exception $e) {
	// perhaps a failed login credential, or perhaps the RDBMS is not running
	echo $e->getMessage();
	exit;
} catch (Zend_Exception $e) {
	// perhaps factory() failed to load the specified Adapter class
	echo $e->getMessage();
	exit;
}


if ($db->fetchOne("SELECT COUNT(*) FROM cms_users") != 0) {
	$gods = $db->fetchOne("SELECT `value` FROM cms_environment WHERE site_id=0 AND `key`='gods'");
	if (isset($_SERVER['PHP_AUTH_USER'])) {
		$password = $db->fetchOne("SELECT password FROM cms_users WHERE username=? AND id IN ({$gods})", $_SERVER['PHP_AUTH_USER']);
		if (!$_SERVER['PHP_AUTH_PW'] or !Password::auth($_SERVER['PHP_AUTH_PW'], $password)) {
			header('WWW-Authenticate: Basic realm="Setup"');
		    header('HTTP/1.0 401 Unauthorized');
			echo "Access denied\n";
			exit;
		}
	} else {
		header('WWW-Authenticate: Basic realm="Setup"');
	    header('HTTP/1.0 401 Unauthorized');
		echo "Access denied\n";
		exit;
	}
}


$site = array(
	'domain_name'  => $_SERVER['HTTP_HOST'],
	'domain_regex' => '^' . str_replace('.', '\.', $_SERVER['HTTP_HOST']) . '$',
	'home_dir'     => "/sites/{$_SERVER['HTTP_HOST']}"
);

if ($existing = $db->fetchRow("SELECT * FROM cms_sites WHERE domain_name=? OR ? REGEXP domain_regex", array($site['domain_name'], $site['domain_name']))) {
	echo "Domain exists:<br />\n";
	echo "<pre>";
	print_r($existing);
	echo "</pre>";
} else {
	$db->insert('cms_sites', $site);
	$site_id = $db->lastInsertId();
	
	$db->insert('cms_users', array(
		'site_id'  => $site_id,
		'created'  => new Zend_Db_Expr('NOW()'),
		'modified' => new Zend_Db_Expr('NOW()'),
		'username' => 'admin',
		'password' => Password::hash('admin'),
		'user_type' => 2
	));
	
	$db->insert('site_templates', array(
		'site_id' => $site_id,
		'title'   => 'Default',
		'file'    => 'default.tpl.html',
		'sort'    => 10
	));
	$template_id = $db->lastInsertId();
	
	$db->insert('site_pages', array(
		'site_id'   => $site_id,
		'parent_id' => 0,
		'sort'      => 10
	));
	$page_id = $db->lastInsertId();
	
	$db->insert('site_pages_revisions', array(
		'page_id'     => $page_id,
		'timestamp'    => new Zend_Db_Expr('NOW()'),
		'title'       => 'Home',
		'template_id' => $template_id
	));
	$revision_id = $db->lastInsertId();
	$db->update('site_pages', array('revision_id' => $revision_id), $db->quoteInto("id=?", $page_id));
	
	$db->insert('cms_images_folders', array(
		'site_id' => $site_id,
		'parent_id' => 0,
		'title' => 'Images'
	));
	
	$db->insert('cms_files_folders', array(
		'site_id' => $site_id,
		'parent_id' => 0,
		'title' => 'Files'
	));
	
	echo "Complete: <a href='/admin/'>login</a>\n";
	
}


/*
 * Class autoloader - currently just configured for Zend
 * style.  Replaces _ with / and adds .php
 *
 */
function __autoload($class) {
	$class = str_replace('_', '/', $class) . '.php';
	require_once($class);
}

